package com.ease.model.util;

import org.postgis.LineString;
import org.postgis.LinearRing;
import org.postgis.PGgeometry;
import org.postgis.Point;
import org.postgis.Polygon;

import com.ease.model.type.GeoLine;
import com.ease.model.type.GeoPoint;
import com.ease.model.type.GeoPolygon;

public class PostgreSqlSpatialGeometryUtil {

	public static GeoLine toGeoLine(PGgeometry geometry) {
		if (null == geometry) {
			return null;
		}
		LineString lineString = (LineString) geometry.getGeometry();

		GeoLine geoLine = new GeoLine();

		for (Point point : lineString.getPoints()) {
			geoLine.addGeoPoint(toGeoPoint(point));
		}

		return geoLine;
	}

	public static GeoPolygon toGeoPolygon(PGgeometry geometry) {
		if (null == geometry) {
			return null;
		}
		Polygon polygon = (Polygon) geometry.getGeometry();

		GeoPolygon geoPolygon = new GeoPolygon();

		int ilen = polygon.numRings();

		for (int i = 0; i < ilen; i++) {
			LinearRing linearRing = polygon.getRing(i);

			int jlen = linearRing.numPoints();
			for (int j = 0; j < jlen; j++) {
				Point point = linearRing.getPoint(j);
				if (null != point) {
					geoPolygon.addGeoPoint(toGeoPoint(point));
				}
			}
		}
		return geoPolygon;
	}

	public static GeoPoint toGeoPoint(Point point) {
		if (null == point) {
			return null;
		}
		GeoPoint geoPoint = new GeoPoint(point.getX(), point.getY(), point.getZ(), point.getM());

		return geoPoint;
	}

	public static PGgeometry fromGeoLine(GeoLine geoLine) {
		return null;// TBD
	}

}
